<template>
  <div class="simple-map-test">
    <div class="map-header">
      <h3>地图测试</h3>
      <el-button @click="testMap" type="primary" size="small">测试地图</el-button>
    </div>
    <div ref="mapContainer" class="map-container"></div>
    <div class="map-info">
      <p>状态: {{ mapStatus }}</p>
      <p>房源数量: {{ roomList.length }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { MAP_CONFIG } from '@/config/map'

const mapContainer = ref(null)
const map = ref(null)
const mapStatus = ref('未初始化')
const roomList = ref([
  {
    id: 1,
    title: '测试房源1',
    latitude: 39.908823,
    longitude: 116.397470,
    price: 3000
  },
  {
    id: 2,
    title: '测试房源2',
    latitude: 39.918823,
    longitude: 116.407470,
    price: 3500
  }
])

const testMap = async () => {
  mapStatus.value = '正在初始化...'
  
  try {
    // 检查腾讯地图SDK是否加载
    if (!window.TMap) {
      throw new Error('腾讯地图SDK未加载')
    }
    
    // 检查API密钥
    if (!MAP_CONFIG.API_KEY || MAP_CONFIG.API_KEY === 'YOUR_TENCENT_MAP_KEY') {
      throw new Error('API密钥未配置')
    }
    
    // 创建地图实例
    map.value = new window.TMap.Map(mapContainer.value, {
      center: new window.TMap.LatLng(39.908823, 116.397470),
      zoom: 12,
      mapTypeId: 1 // 使用数字常量：1=街道图，2=卫星图
    })
    
    // 添加标记
    const marker = new window.TMap.MultiMarker({
      map: map.value,
      styles: {
        default: new window.TMap.MarkerStyle({
          width: 30,
          height: 30,
          anchor: { x: 15, y: 15 },
          src: 'data:image/svg+xml;base64,' + btoa(`
            <svg width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg">
              <circle cx="15" cy="15" r="12" fill="#1890ff" stroke="#fff" stroke-width="2"/>
              <text x="15" y="20" text-anchor="middle" fill="white" font-size="12" font-weight="bold">1</text>
            </svg>
          `)
        })
      },
      geometries: roomList.value.map(room => ({
        position: new window.TMap.LatLng(room.latitude, room.longitude),
        id: room.id,
        properties: {
          title: room.title,
          price: room.price
        }
      }))
    })
    
    mapStatus.value = '初始化成功'
    ElMessage.success('地图初始化成功！')
    
  } catch (error) {
    console.error('地图测试失败:', error)
    mapStatus.value = `初始化失败: ${error.message}`
    ElMessage.error(`地图测试失败: ${error.message}`)
  }
}

onMounted(() => {
  nextTick(() => {
    testMap()
  })
})
</script>

<style scoped>
.simple-map-test {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.map-container {
  width: 100%;
  height: 400px;
  border: 1px solid #ddd;
  border-radius: 8px;
  margin-bottom: 16px;
}

.map-info {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
}

.map-info p {
  margin: 4px 0;
  font-size: 14px;
}
</style>
